<?php

namespace app\admin\server;

use think\Env;
use think\Exception;
use think\Loader;
use WXBizMsgCrypt;

Loader::import('weworkapi_php-master.callback.WXBizMsgCrypt');// 括号中为类库路径

class QiweiNewApplicationsServer extends BaseServer
{
    protected $token;
    protected $encodingAESKey;
    protected $corpId;
    protected $Secret;

    public function __construct()
    {
        $this->token = Env::get('qiwei_new_applications.token', '');
        $this->encodingAESKey = Env::get('qiwei_new_applications.EncodingAESKey', '');
        $this->corpId = Env::get('qiwei.CorpId', '');
        $this->Secret = Env::get('qiwei_new_applications.Secret', '');
    }

    /***
     * 检验消息的真实性，并且获取解密后的明文.
     * application/library/weworkapi_php-master/callback/Sample.php
     * @param $echostr
     * @param $msg_signature
     * @param $timestamp
     * @param $nonce
     * @param $sMsg
     * @return true
     * @throws Exception
     */
    public function VerifyURL($echostr, $msg_signature, $timestamp, $nonce)
    {
        // file_put_contents('./result.txt', '');
        // file_put_contents('./result.txt', 'start:'.date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND | LOCK_EX);
        try {
            $wxcpt = new WXBizMsgCrypt($this->token, $this->encodingAESKey, $this->corpId);
            $sMsg = "";
            // file_put_contents('./result.txt', '1'.PHP_EOL, FILE_APPEND | LOCK_EX);
            $errCode = $wxcpt->VerifyURL($msg_signature, $timestamp, $nonce, $echostr, $sMsg);
            // file_put_contents('./result.txt', '$errCode='.$errCode.PHP_EOL, FILE_APPEND | LOCK_EX);
            // file_put_contents('./result.txt', '$sMsg='.$sMsg.PHP_EOL, FILE_APPEND | LOCK_EX);
            if($errCode == 0) {
                /*  var_dump($sMsg);
                  echo $echostr;*/
                return $sMsg;
            } else {
                /* print("ERR: " . $errCode . "\n\n");*/
                throw new Exception($sMsg, $errCode);
            }
        } catch(\Exception $e) {
            // file_put_contents('./result.txt', 'decryptMsg_error='.$e->getMessage().PHP_EOL, FILE_APPEND | LOCK_EX);
            throw new Exception($e->getMessage());
        }
        // file_put_contents('./result.txt', 'end:'.date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND | LOCK_EX);
    }
}